home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / perl5 / HTTP / Request / Common.pm
Encoding:
Perl POD Document  |  2008-10-20  |  13.8 KB  |  508 lines

  1. package HTTP::Request::Common;
  2.  
  3. use strict;
  4. use vars qw(@EXPORT @EXPORT_OK $VERSION $DYNAMIC_FILE_UPLOAD);
  5.  
  6. $DYNAMIC_FILE_UPLOAD ||= 0;  # make it defined (don't know why)
  7.  
  8. require Exporter;
  9. *import = \&Exporter::import;
  10. @EXPORT =qw(GET HEAD PUT POST);
  11. @EXPORT_OK = qw($DYNAMIC_FILE_UPLOAD DELETE);
  12.  
  13. require HTTP::Request;
  14. use Carp();
  15.  
  16. $VERSION = "5.817";
  17.  
  18. my $CRLF = "\015\012";   # "\r\n" is not portable
  19.  
  20. sub GET  { _simple_req('GET',  @_); }
  21. sub HEAD { _simple_req('HEAD', @_); }
  22. sub PUT  { _simple_req('PUT' , @_); }
  23. sub DELETE { _simple_req('DELETE', @_); }
  24.  
  25. sub POST
  26. {
  27.     my $url = shift;
  28.     my $req = HTTP::Request->new(POST => $url);
  29.     my $content;
  30.     $content = shift if @_ and ref $_[0];
  31.     my($k, $v);
  32.     while (($k,$v) = splice(@_, 0, 2)) {
  33.     if (lc($k) eq 'content') {
  34.         $content = $v;
  35.     }
  36.     else {
  37.         $req->push_header($k, $v);
  38.     }
  39.     }
  40.     my $ct = $req->header('Content-Type');
  41.     unless ($ct) {
  42.     $ct = 'application/x-www-form-urlencoded';
  43.     }
  44.     elsif ($ct eq 'form-data') {
  45.     $ct = 'multipart/form-data';
  46.     }
  47.  
  48.     if (ref $content) {
  49.     if ($ct =~ m,^multipart/form-data\s*(;|$),i) {
  50.         require HTTP::Headers::Util;
  51.         my @v = HTTP::Headers::Util::split_header_words($ct);
  52.         Carp::carp("Multiple Content-Type headers") if @v > 1;
  53.         @v = @{$v[0]};
  54.  
  55.         my $boundary;
  56.         my $boundary_index;
  57.         for (my @tmp = @v; @tmp;) {
  58.         my($k, $v) = splice(@tmp, 0, 2);
  59.         if ($k eq "boundary") {
  60.             $boundary = $v;
  61.             $boundary_index = @v - @tmp - 1;
  62.             last;
  63.         }
  64.         }
  65.  
  66.         ($content, $boundary) = form_data($content, $boundary, $req);
  67.  
  68.         if ($boundary_index) {
  69.         $v[$boundary_index] = $boundary;
  70.         }
  71.         else {
  72.         push(@v, boundary => $boundary);
  73.         }
  74.  
  75.         $ct = HTTP::Headers::Util::join_header_words(@v);
  76.     }
  77.     else {
  78.         # We use a temporary URI object to format
  79.         # the application/x-www-form-urlencoded content.
  80.         require URI;
  81.         my $url = URI->new('http:');
  82.         $url->query_form(ref($content) eq "HASH" ? %$content : @$content);
  83.         $content = $url->query;
  84.     }
  85.     }
  86.  
  87.     $req->header('Content-Type' => $ct);  # might be redundant
  88.     if (defined($content)) {
  89.     $req->header('Content-Length' =>
  90.              length($content)) unless ref($content);
  91.     $req->content($content);
  92.     }
  93.     else {
  94.         $req->header('Content-Length' => 0);
  95.     }
  96.     $req;
  97. }
  98.  
  99.  
  100. sub _simple_req
  101. {
  102.     my($method, $url) = splice(@_, 0, 2);
  103.     my $req = HTTP::Request->new($method => $url);
  104.     my($k, $v);
  105.     while (($k,$v) = splice(@_, 0, 2)) {
  106.     if (lc($k) eq 'content') {
  107.         $req->add_content($v);
  108.             $req->header("Content-Length", length(${$req->content_ref}));
  109.     }
  110.     else {
  111.         $req->push_header($k, $v);
  112.     }
  113.     }
  114.     $req;
  115. }
  116.  
  117.  
  118. sub form_data   # RFC1867
  119. {
  120.     my($data, $boundary, $req) = @_;
  121.     my @data = ref($data) eq "HASH" ? %$data : @$data;  # copy
  122.     my $fhparts;
  123.     my @parts;
  124.     my($k,$v);
  125.     while (($k,$v) = splice(@data, 0, 2)) {
  126.     if (!ref($v)) {
  127.         $k =~ s/([\\\"])/\\$1/g;  # escape quotes and backslashes
  128.         push(@parts,
  129.          qq(Content-Disposition: form-data; name="$k"$CRLF$CRLF$v));
  130.     }
  131.     else {
  132.         my($file, $usename, @headers) = @$v;
  133.         unless (defined $usename) {
  134.         $usename = $file;
  135.         $usename =~ s,.*/,, if defined($usename);
  136.         }
  137.             $k =~ s/([\\\"])/\\$1/g;
  138.         my $disp = qq(form-data; name="$k");
  139.             if (defined($usename) and length($usename)) {
  140.                 $usename =~ s/([\\\"])/\\$1/g;
  141.                 $disp .= qq(; filename="$usename");
  142.             }
  143.         my $content = "";
  144.         my $h = HTTP::Headers->new(@headers);
  145.         if ($file) {
  146.         open(my $fh, "<", $file) or Carp::croak("Can't open file $file: $!");
  147.         binmode($fh);
  148.         if ($DYNAMIC_FILE_UPLOAD) {
  149.             # will read file later, close it now in order to
  150.                     # not accumulate to many open file handles
  151.                     close($fh);
  152.             $content = \$file;
  153.         }
  154.         else {
  155.             local($/) = undef; # slurp files
  156.             $content = <$fh>;
  157.             close($fh);
  158.         }
  159.         unless ($h->header("Content-Type")) {
  160.             require LWP::MediaTypes;
  161.             LWP::MediaTypes::guess_media_type($file, $h);
  162.         }
  163.         }
  164.         if ($h->header("Content-Disposition")) {
  165.         # just to get it sorted first
  166.         $disp = $h->header("Content-Disposition");
  167.         $h->remove_header("Content-Disposition");
  168.         }
  169.         if ($h->header("Content")) {
  170.         $content = $h->header("Content");
  171.         $h->remove_header("Content");
  172.         }
  173.         my $head = join($CRLF, "Content-Disposition: $disp",
  174.                        $h->as_string($CRLF),
  175.                        "");
  176.         if (ref $content) {
  177.         push(@parts, [$head, $$content]);
  178.         $fhparts++;
  179.         }
  180.         else {
  181.         push(@parts, $head . $content);
  182.         }
  183.     }
  184.     }
  185.     return ("", "none") unless @parts;
  186.  
  187.     my $content;
  188.     if ($fhparts) {
  189.     $boundary = boundary(10) # hopefully enough randomness
  190.         unless $boundary;
  191.  
  192.     # add the boundaries to the @parts array
  193.     for (1..@parts-1) {
  194.         splice(@parts, $_*2-1, 0, "$CRLF--$boundary$CRLF");
  195.     }
  196.     unshift(@parts, "--$boundary$CRLF");
  197.     push(@parts, "$CRLF--$boundary--$CRLF");
  198.  
  199.     # See if we can generate Content-Length header
  200.     my $length = 0;
  201.     for (@parts) {
  202.         if (ref $_) {
  203.          my ($head, $f) = @$_;
  204.         my $file_size;
  205.         unless ( -f $f && ($file_size = -s _) ) {
  206.             # The file is either a dynamic file like /dev/audio
  207.             # or perhaps a file in the /proc file system where
  208.             # stat may return a 0 size even though reading it
  209.             # will produce data.  So we cannot make
  210.             # a Content-Length header.  
  211.             undef $length;
  212.             last;
  213.         }
  214.             $length += $file_size + length $head;
  215.         }
  216.         else {
  217.         $length += length;
  218.         }
  219.         }
  220.         $length && $req->header('Content-Length' => $length);
  221.  
  222.     # set up a closure that will return content piecemeal
  223.     $content = sub {
  224.         for (;;) {
  225.         unless (@parts) {
  226.             defined $length && $length != 0 &&
  227.                 Carp::croak "length of data sent did not match calculated Content-Length header.  Probably because uploaded file changed in size during transfer.";
  228.             return;
  229.         }
  230.         my $p = shift @parts;
  231.         unless (ref $p) {
  232.             $p .= shift @parts while @parts && !ref($parts[0]);
  233.             defined $length && ($length -= length $p);
  234.             return $p;
  235.         }
  236.         my($buf, $fh) = @$p;
  237.                 unless (ref($fh)) {
  238.                     my $file = $fh;
  239.                     undef($fh);
  240.                     open($fh, "<", $file) || Carp::croak("Can't open file $file: $!");
  241.                     binmode($fh);
  242.                 }
  243.         my $buflength = length $buf;
  244.         my $n = read($fh, $buf, 2048, $buflength);
  245.         if ($n) {
  246.             $buflength += $n;
  247.             unshift(@parts, ["", $fh]);
  248.         }
  249.         else {
  250.             close($fh);
  251.         }
  252.         if ($buflength) {
  253.             defined $length && ($length -= $buflength);
  254.             return $buf 
  255.             }
  256.         }
  257.     };
  258.  
  259.     }
  260.     else {
  261.     $boundary = boundary() unless $boundary;
  262.  
  263.     my $bno = 0;
  264.       CHECK_BOUNDARY:
  265.     {
  266.         for (@parts) {
  267.         if (index($_, $boundary) >= 0) {
  268.             # must have a better boundary
  269.             $boundary = boundary(++$bno);
  270.             redo CHECK_BOUNDARY;
  271.         }
  272.         }
  273.         last;
  274.     }
  275.     $content = "--$boundary$CRLF" .
  276.                join("$CRLF--$boundary$CRLF", @parts) .
  277.            "$CRLF--$boundary--$CRLF";
  278.     }
  279.  
  280.     wantarray ? ($content, $boundary) : $content;
  281. }
  282.  
  283.  
  284. sub boundary
  285. {
  286.     my $size = shift || return "xYzZY";
  287.     require MIME::Base64;
  288.     my $b = MIME::Base64::encode(join("", map chr(rand(256)), 1..$size*3), "");
  289.     $b =~ s/[\W]/X/g;  # ensure alnum only
  290.     $b;
  291. }
  292.  
  293. 1;
  294.  
  295. __END__
  296.  
  297. =head1 NAME
  298.  
  299. HTTP::Request::Common - Construct common HTTP::Request objects
  300.  
  301. =head1 SYNOPSIS
  302.  
  303.   use HTTP::Request::Common;
  304.   $ua = LWP::UserAgent->new;
  305.   $ua->request(GET 'http://www.sn.no/');
  306.   $ua->request(POST 'http://somewhere/foo', [foo => bar, bar => foo]);
  307.  
  308. =head1 DESCRIPTION
  309.  
  310. This module provide functions that return newly created C<HTTP::Request>
  311. objects.  These functions are usually more convenient to use than the
  312. standard C<HTTP::Request> constructor for the most common requests.  The
  313. following functions are provided:
  314.  
  315. =over 4
  316.  
  317. =item GET $url
  318.  
  319. =item GET $url, Header => Value,...
  320.  
  321. The GET() function returns an C<HTTP::Request> object initialized with
  322. the "GET" method and the specified URL.  It is roughly equivalent to the
  323. following call
  324.  
  325.   HTTP::Request->new(
  326.      GET => $url,
  327.      HTTP::Headers->new(Header => Value,...),
  328.   )
  329.  
  330. but is less cluttered.  What is different is that a header named
  331. C<Content> will initialize the content part of the request instead of
  332. setting a header field.  Note that GET requests should normally not
  333. have a content, so this hack makes more sense for the PUT() and POST()
  334. functions described below.
  335.  
  336. The get(...) method of C<LWP::UserAgent> exists as a shortcut for
  337. $ua->request(GET ...).
  338.  
  339. =item HEAD $url
  340.  
  341. =item HEAD $url, Header => Value,...
  342.  
  343. Like GET() but the method in the request is "HEAD".
  344.  
  345. The head(...)  method of "LWP::UserAgent" exists as a shortcut for
  346. $ua->request(HEAD ...).
  347.  
  348. =item PUT $url
  349.  
  350. =item PUT $url, Header => Value,...
  351.  
  352. =item PUT $url, Header => Value,..., Content => $content
  353.  
  354. Like GET() but the method in the request is "PUT".
  355.  
  356. The content of the request can be specified using the "Content"
  357. pseudo-header.  This steals a bit of the header field namespace as
  358. there is no way to directly specify a header that is actually called
  359. "Content".  If you really need this you must update the request
  360. returned in a separate statement.
  361.  
  362. =item DELETE $url
  363.  
  364. =item DELETE $url, Header => Value,...
  365.  
  366. Like GET() but the method in the request is "DELETE".  This funciton
  367. is not exported by default.
  368.  
  369. =item POST $url
  370.  
  371. =item POST $url, Header => Value,...
  372.  
  373. =item POST $url, $form_ref, Header => Value,...
  374.  
  375. =item POST $url, Header => Value,..., Content => $form_ref
  376.  
  377. =item POST $url, Header => Value,..., Content => $content
  378.  
  379. This works mostly like PUT() with "POST" as the method, but this
  380. function also takes a second optional array or hash reference
  381. parameter $form_ref.  As for PUT() the content can also be specified
  382. directly using the "Content" pseudo-header, and you may also provide
  383. the $form_ref this way.
  384.  
  385. The $form_ref argument can be used to pass key/value pairs for the
  386. form content.  By default we will initialize a request using the
  387. C<application/x-www-form-urlencoded> content type.  This means that
  388. you can emulate a HTML E<lt>form> POSTing like this:
  389.  
  390.   POST 'http://www.perl.org/survey.cgi',
  391.        [ name   => 'Gisle Aas',
  392.          email  => 'gisle@aas.no',
  393.          gender => 'M',
  394.          born   => '1964',
  395.          perc   => '3%',
  396.        ];
  397.  
  398. This will create a HTTP::Request object that looks like this:
  399.  
  400.   POST http://www.perl.org/survey.cgi
  401.   Content-Length: 66
  402.   Content-Type: application/x-www-form-urlencoded
  403.  
  404.   name=Gisle%20Aas&email=gisle%40aas.no&gender=M&born=1964&perc=3%25
  405.  
  406. Multivalued form fields can be specified by either repeating the field
  407. name or by passing the value as an array reference.
  408.  
  409. The POST method also supports the C<multipart/form-data> content used
  410. for I<Form-based File Upload> as specified in RFC 1867.  You trigger
  411. this content format by specifying a content type of C<'form-data'> as
  412. one of the request headers.  If one of the values in the $form_ref is
  413. an array reference, then it is treated as a file part specification
  414. with the following interpretation:
  415.  
  416.   [ $file, $filename, Header => Value... ]
  417.   [ undef, $filename, Header => Value,..., Content => $content ]
  418.  
  419. The first value in the array ($file) is the name of a file to open.
  420. This file will be read and its content placed in the request.  The
  421. routine will croak if the file can't be opened.  Use an C<undef> as
  422. $file value if you want to specify the content directly with a
  423. C<Content> header.  The $filename is the filename to report in the
  424. request.  If this value is undefined, then the basename of the $file
  425. will be used.  You can specify an empty string as $filename if you
  426. want to suppress sending the filename when you provide a $file value.
  427.  
  428. If a $file is provided by no C<Content-Type> header, then C<Content-Type>
  429. and C<Content-Encoding> will be filled in automatically with the values
  430. returned by LWP::MediaTypes::guess_media_type()
  431.  
  432. Sending my F<~/.profile> to the survey used as example above can be
  433. achieved by this:
  434.  
  435.   POST 'http://www.perl.org/survey.cgi',
  436.        Content_Type => 'form-data',
  437.        Content      => [ name  => 'Gisle Aas',
  438.                          email => 'gisle@aas.no',
  439.                          gender => 'M',
  440.                          born   => '1964',
  441.                          init   => ["$ENV{HOME}/.profile"],
  442.                        ]
  443.  
  444. This will create a HTTP::Request object that almost looks this (the
  445. boundary and the content of your F<~/.profile> is likely to be
  446. different):
  447.  
  448.   POST http://www.perl.org/survey.cgi
  449.   Content-Length: 388
  450.   Content-Type: multipart/form-data; boundary="6G+f"
  451.  
  452.   --6G+f
  453.   Content-Disposition: form-data; name="name"
  454.  
  455.   Gisle Aas
  456.   --6G+f
  457.   Content-Disposition: form-data; name="email"
  458.  
  459.   gisle@aas.no
  460.   --6G+f
  461.   Content-Disposition: form-data; name="gender"
  462.  
  463.   M
  464.   --6G+f
  465.   Content-Disposition: form-data; name="born"
  466.  
  467.   1964
  468.   --6G+f
  469.   Content-Disposition: form-data; name="init"; filename=".profile"
  470.   Content-Type: text/plain
  471.  
  472.   PATH=/local/perl/bin:$PATH
  473.   export PATH
  474.  
  475.   --6G+f--
  476.  
  477. If you set the $DYNAMIC_FILE_UPLOAD variable (exportable) to some TRUE
  478. value, then you get back a request object with a subroutine closure as
  479. the content attribute.  This subroutine will read the content of any
  480. files on demand and return it in suitable chunks.  This allow you to
  481. upload arbitrary big files without using lots of memory.  You can even
  482. upload infinite files like F</dev/audio> if you wish; however, if
  483. the file is not a plain file, there will be no Content-Length header
  484. defined for the request.  Not all servers (or server
  485. applications) like this.  Also, if the file(s) change in size between
  486. the time the Content-Length is calculated and the time that the last
  487. chunk is delivered, the subroutine will C<Croak>.
  488.  
  489. The post(...)  method of "LWP::UserAgent" exists as a shortcut for
  490. $ua->request(POST ...).
  491.  
  492. =back
  493.  
  494. =head1 SEE ALSO
  495.  
  496. L<HTTP::Request>, L<LWP::UserAgent>
  497.  
  498.  
  499. =head1 COPYRIGHT
  500.  
  501. Copyright 1997-2004, Gisle Aas
  502.  
  503. This library is free software; you can redistribute it and/or
  504. modify it under the same terms as Perl itself.
  505.  
  506. =cut
  507.  
  508.